package ute.tlcn.struts2hibernate.action;

import java.util.List;

import ute.tlcn.struts2hibernate.dao.HibernateUtil;
import ute.tlcn.struts2hibernate.javabean.Item;
import ute.tlcn.struts2hibernate.service.ItemBO;
import ute.tlcn.struts2hibernate.service.ItemBOImpl;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.util.ValueStack;

public class ItemAction extends ActionSupport implements ModelDriven<Item> {

	private static final long serialVersionUID = 3033642935282903352L;
	
	private Item item = new Item();
	
	public String list() throws Exception {
		try {
			HibernateUtil.getSesisonFactory().getCurrentSession().beginTransaction();
			List<Item> items = new ItemBOImpl().list();
			for(Item i : items) {
				System.out.println(i.getName());
			}
			ValueStack stack = ActionContext.getContext().getValueStack();
			stack.set("items", items);
			HibernateUtil.getSesisonFactory().getCurrentSession().getTransaction().commit();
		} catch(Exception e) {
			HibernateUtil.getSesisonFactory().getCurrentSession().getTransaction().rollback();
		}
		
		return "list";
	}
	
	public String save() {
		try {
			HibernateUtil.getSesisonFactory().getCurrentSession().beginTransaction();
			ItemBO bo = new ItemBOImpl();
			if(item.getId() != null) {
				bo.update(item);
			} else {
				bo.insert(item);
			}
			HibernateUtil.getSesisonFactory().getCurrentSession().getTransaction().commit();
			return "rlist";
		} catch(Exception e) {
			HibernateUtil.getSesisonFactory().getCurrentSession().getTransaction().rollback();
			return "error";
		}
	}
	
	public String remove() {
		try {
			HibernateUtil.getSesisonFactory().getCurrentSession().beginTransaction();
			ItemBO bo = new ItemBOImpl();
			bo.delete(item.getId());
			HibernateUtil.getSesisonFactory().getCurrentSession().getTransaction().commit();
			return "rlist";
		} catch(Exception e) {
			e.printStackTrace();
			HibernateUtil.getSesisonFactory().getCurrentSession().getTransaction().rollback();
			return "error";
		}
	}
	
	public String update() {
		try {
			HibernateUtil.getSesisonFactory().getCurrentSession().beginTransaction();
			ItemBO bo = new ItemBOImpl();
			item = bo.findById(item.getId());
			HibernateUtil.getSesisonFactory().getCurrentSession().getTransaction().commit();
			return "update";
		} catch(Exception e) {
			HibernateUtil.getSesisonFactory().getCurrentSession().getTransaction().rollback();
			return "error";
		}
	}

	@Override
	public Item getModel() {
		return item;
	}
}
